package cn.itcast.tant_test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;


public class TestGetThreadTime {

    public static void main(String[] args) throws InterruptedException {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        if (threadMXBean.isThreadCpuTimeSupported() && threadMXBean.isThreadCpuTimeEnabled()) {
            // TODO ...你的代码
            for (int i = 1; i <= 26; i++) {
                readFromFile(i);
            }

            long threadId = Thread.currentThread().getId();
            long cpuTime = threadMXBean.getThreadCpuTime(threadId);
            long userTime = threadMXBean.getThreadUserTime(threadId);
            long waitTime = cpuTime - userTime;
            System.out.println("总时间(CPU计算时间+等待时间) : " + cpuTime + " ns");
            System.out.println("CPU计算时间: " + userTime + " ns");
            System.out.println("等待时间: " + waitTime + " ns");
            BigDecimal multiply = new BigDecimal(userTime).divide(new BigDecimal(cpuTime), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            System.out.println("CPU计算时间/总时间: " + multiply + "%");
        } else {
            System.out.println("Thread CPU time is not supported or enabled.");
        }

    }


    public static List<String> readFromFile(int i) {
        ArrayList<String> words = new ArrayList<>();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("tmp/" + i + ".txt")))) {
            while (true) {
                String word = in.readLine();
                if (word == null) {
                    break;
                }
                words.add(word);
            }
            return words;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

